package cn.onein.edu.util;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 支付服务的工具类
 * @author Upton
 *
 */
public class PaymentUtil {	
	private static Random seedRandom = new Random(new Date().getTime());
	
	private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
		"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	
	private static String byteArrayToHexString(byte b[]) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++)
			resultSb.append(byteToHexString(b[i]));

		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n += 256;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	/**
	 * 为支付参数签名
	 * @param origin
	 * @param charsetname
	 * @return
	 */
	public static String MD5Encode(String origin, String charsetname) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (charsetname == null || "".equals(charsetname)){
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes()));
			}
			else{
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes(charsetname)));
			}
		} catch (Exception exception) {
		}
		return resultString;
	}
	
	/**
	 * 生成一个订单号
	 * @return 返回一个20位的订单号,格式：17位yyyyMMddHHmmssSSS + 3位随机数
	 */
	public static String generateNewOrderNo(){
		Date now = new Date();		
		String timespan = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(now);		
		
		Random realRandom = new Random(seedRandom.nextLong());
		
		int nextInt = realRandom.nextInt(1000); // 0 <= nextInt <= 999
		if(nextInt < 100){
			nextInt += 100;
		} // 100 <= nextInt <= 999
		
		return timespan + String.valueOf(nextInt); //总共20位
	}
	
	/**
	 * 获取当前时间 yyyyMMddHHmmss
	 * @return String
	 */ 
	public static String getCurrTime() {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String s = outFormat.format(now);
		return s;
	}
	
	public static void main(String[] args){
		for(int i = 0; i < 100; i++){
			String no = generateNewOrderNo();
			
			//if(no.length() != 20)
				System.out.println(no);
		}
		
		System.out.println("OK");
	}
}
